<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content release" v-show="true">
      <heading grade="1">填写详情</heading>
      <el-form :model="form" :rules="rules" label-width="142px" ref="form" v-bind="getFormProps()">
        <!-- 固定块 -->
        <heading grade="2">基本信息</heading>
        <el-form-item label="服务类目："
          prop="serviceCate"
          :rules="[
            { required: !0, message: '请选择服务类目'},
          ]">
          <el-cascader
            class="serviceCas"
            :disabled="!!editorType"
            label="cateName"
            v-model="form.serviceCate"
            :grade="2"
            :props="{
              value: 'cateCode',
              label: 'cateName'
            }"
            :options="categoryList"
            @change="handleCateChange"
            @active-item-change="handleCateItemChange"/>
        </el-form-item>
        <el-form-item label="名称："
          prop="goodsName"
          :rules="[
            { required: !0, message: '名称不能为空'},
          ]">
          <el-col :span="20">
            <x-input v-model="form.goodsName" :maxlength="60" />
          </el-col>
        </el-form-item> 
        <el-form-item label="卖点：" prop="sellPoint">
          <el-col :span="20">
            <x-input v-model="form.sellPoint" :maxlength="150" type="textarea" :rows="4"/>
          </el-col>
        </el-form-item>
        <!--后台配置块  -->
        <el-row v-show="form.serviceCate.length">
          <heading grade="2">基本属性</heading>
          <el-form-item label="品牌：" prop="brand"
            :rules="[
              { required: !1, message: '请选择品牌'},
            ]">
            <el-col :span="20">
              <el-select v-model="form.brand" placeholder="请选择" class="input-block">
                <el-option v-for="item in brandList" :key="item.brandCode" :label="item.brandName" :value="item.brandCode" />
              </el-select>
            </el-col>
          </el-form-item>
          <form-item
            v-for="(item, index) in form.basicProps"
            formKey="basicProps"
            :isEditor="!!editorType"
            :key="item.index"
            :label="item.nameText"
            :index="index"
            :data.sync="item"/>
        </el-row>
        <el-row v-show="form.serviceCate.length">
          <heading grade="2">销售信息</heading>
          <!-- 销售属性 -->
          <el-form-item label="销售属性："
            :rules="[
              {required: !0, message: '请选择销售属性'}
            ]">
            <el-row
              class="sale-props-item"
              v-for="(item, index) in form.saleProps"
              :key="index">
              <span class="group-title">{{item.attrName}}</span>
              <checkbox-groups
                v-model="item.data"
                :customGroupState="customGroupState"
                :editorType="editorType"
                :isTrain="isTrain"
                :min="1"
                :data="item"
                :index="index"
                :groupLen="form.saleProps.length"
                @change="handleSalePropsChange"/>
            </el-row>
          </el-form-item>
          <!-- 销售规格 -->
          <el-form-item label="销售规格："
            prop="tableData"
            :rules="[
              {required: !0, message: '请输入销售规格'},
              Object.assign({}, validator.rule.saleArray,{message: '请输入数量,数量为正整数'})
            ]">
            <el-col :span="24">
              <div class="tips tips-left">限购数量为<span class="num">0</span>时，代表不限购</div>
              <sale-spec-table
                :tableData.sync="form.tableData"
                :columData="form.saleProps"
                @change="handleTableDataChange"/>
            </el-col>
          </el-form-item>
        </el-row>
        <heading grade="2">详情描述</heading>
        <el-form-item label="上传图片："
          prop="imageList"
          :rules="[
            { required: true, message: '请上传图片'},
          ]">
          <img-group-upload v-model="form.imageList" :limit="10" />
        </el-form-item>
        <!-- 赛事详情 -->
        <el-form-item label="服务详情："
          prop="goodsDesc"
          :rules="[
            { required: !0, message: '请输入服务详情'}
          ]">
          <editor v-model="form.goodsDesc" :maxlength="10000"/>                 
        </el-form-item>
        <!-- 手机端描述 -->
        <!-- <el-form-item label="手机端描述："
          prop="goodsMoblieDesc"
          :rules="[
          { required: true, message: '请输入手机端描述'}
          ]">
          <editor-mobile v-model="form.goodsMoblieDesc" :isEditor="!!editorType"/>
        </el-form-item> -->
        <heading grade="2" v-if="isRun || form.otherProps.length || form.buyTimes.length">其他信息</heading>
        <!-- 票务 购买起止时间 -->
        <ticket-times v-if="isTicket" v-model="form.buyTimes"/>
        <form-item
            v-for="(item, index) in form.otherProps"
            formKey="otherProps"
            :isEditor="!!editorType"
            :key="item.index"
            :label="item.nameText"
            :index="index"
            :data.sync="item"/>
        <template v-if="isRun">
          <el-form-item label="报名渠道："
            prop="channelList"
            :rules="[
              { required: true, message: '请选择赛制类型'},
              Object.assign({trigger: 'blur'}, validator.rule.channelArray,{messageNum: '请输入渠道名额,名额为正整数', messageChannel: '渠道名不能相同'})
            ]">
            <base-group :value="form.channelList" @add="handelAddChannel" @remove="handelDelChannel" :max-item="6" :simple-layout="false">
              <template scope="scope">
                <el-row class="mb10" >
                  <el-input class="input-middle" placeholder="请输入报名渠道名称"  v-model="scope.item.channelName" :readonly="!scope.index"/>
                </el-row>
                <el-row :gutter="10">
                  <channel-item
                    :parentIndex="scope.index"
                    v-for="(it,$index) in scope.item.channelsGroup"
                    :parentData="form.channelList"
                    :key="it.item[0].name"
                    :data.sync="it"
                    :index="$index"/>
                </el-row>
              </template>
            </base-group>
          </el-form-item>
        </template>
        <train-sign-filed v-if="isTrain" v-model="form.trainSignFiled"/>
        <!-- 上架时间  -->
        <el-form-item label="上架时间："
          v-if="isTicket"
          prop="shelveTime"
          :rules="shelveTimeRules">
          <el-radio-group v-model="shelfLevel" @change="handleShelfChange">
            <el-radio :label="SHELF_LEVEL.NOW">立即上架</el-radio>
            <el-radio :label="SHELF_LEVEL.TIME">定时上架
              <el-date-picker
                v-show="shelfLevel === SHELF_LEVEL.TIME"
                type="datetime"
                :picker-options="{
                  disabledDate (time) {
                    return time.getTime() < Date.now() - 8.64e7
                  }
                }"
                format="yyyy-MM-dd HH:mm"
                v-model="shelveTime"/>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="button-box">
          <!--loading是必需在绑定的 native-type="submit"修改button type类型-->
          <el-button type="primary"
            native-type="button"
            :loading="draftLoading && loading"
            @click="handleDraft">保存草稿</el-button>
          <el-button native-type="submit" :loading="saveLoading && loading">{{subBtnName}}</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import XInput from 'components/XInput'

import Editor from 'modules/components/Editor'
import BaseGroup from '@/modules/components/BaseGroup'
import InputGroup from 'modules/components/InputGroup'
import ImgGroupUpload from 'modules/components/ImgGroupUpload'
import AddressCascader from 'modules/components/AddressCascader'

import EditorMobile from './components/EditorMobile'
import FormItem from './components/FormItem'
import ChannelItem from './components/ChannelItem'
import CheckboxGroups from './components/CheckboxGroups'
import SaleSpecTable from './components/SaleSpecTable'
import TicketTimes from './components/TicketTimes'
import TrainSignFiled from './components/TrainSignFiled'

import filters from 'src/filters'
import { cloneObj } from 'utils'
import validator from 'utils/validator'
import serviceApi from 'api/service'
import {form} from 'utils/mixins' // 引入form mixin

import {
  RUN_CODE,
  TRAIN_REG,
  TICKET_REG,
  SHELF_LEVEL, // 上架类型
  MATCH_CODE_LIST,
  FORM_TYPE_ENUMS,
  EDIT_TYPE_ENUMS,
  PROPS_TYPE_ENUMS,
  SHELVE_TIME_FORMAT,
  BASE_TABLE_ROW_DATA
} from './constant'

export default {
  mixins: [form],
  components: {
    Editor,
    XInput,
    FormItem,
    BaseGroup,
    InputGroup,
    ChannelItem,
    EditorMobile,
    CheckboxGroups,
    SaleSpecTable,
    AddressCascader,
    ImgGroupUpload,
    TicketTimes,
    TrainSignFiled
  },
  computed: {
    releaseType () {
      let result = 1
      let type = this.$route.params.releaseType
      if (type === 'activity') { // 活动 虚拟商品
        result = 1
      }
      if (type === 'product') { // 实体商品
        result = 2
      }
      return result
    },
    goodsCode () {
      return this.$route.params.goodsCode
    },
    cateCode () {
      return this.$route.params.goodsCateCode
    },
    editorType () {
      return this.$route.params.editType
    },
    serviceType () {
      let type = ''
      type = this.form.serviceCate[1]
      return type - 0
    },
    phoneEditorState () {
      return this.editorType && !this.form.goodsMoblieDesc ? !1 : !0
    },
    subBtnName () {
      return this.editorType === EDIT_TYPE_ENUMS.REPUBLISH ? '重新发布' : '确认提交'
    },
    customGroupState () {
      // 编辑状态下  自定义组别状态
      let curCode = this.form.serviceCate[this.form.serviceCate.length - 1]
      return this.editorType && MATCH_CODE_LIST.includes(curCode)
    },
    shelveTime: {
      set (val) {
        this.form.shelveTime = val ? filters.FormatDate(val, SHELVE_TIME_FORMAT) : ''
      },
      get () {
        return this.form.shelveTime
      }
    }
  },
  created () {
    this.initCateData()
    // window.tyler = this
  },
  data () {
    return {
      SHELF_LEVEL: SHELF_LEVEL,
      saveLoading: !1, // 保存loading
      draftLoading: !1, // 保存草稿loading
      loading: !1, // 必需要返回loading
      validator,
      checked: !1,
      isRun: !1, // 赛事跑步特殊项
      isTicket: !1, // 票务特殊处理
      isTrain: !1, // 培训
      rules: {},
      _categoryList: [], // 未处理的类目
      categoryList: [], // 类目
      brandList: [], // 品牌列表
      basicPropsObj: {}, // 存储基本属性的信息
      // editorData: {},
      groupItems: [],
      shelfLevel: SHELF_LEVEL.NOW, // 上架时间类型
      shelveTimeRules: [{required: !0}],
      form: {
        serviceCate: [], // 服务类目
        goodsName: '', // 商品名称
        sellPoint: '', // 卖点
        brand: '',
        basicProps: [], // 基本属性
        saleProps: [], // 销售属性
        otherProps: [], // 其他信息
        tableData: [],
        imageList: [], // 上传图片
        goodsDesc: '',
        goodsMoblieDesc: '', // 手机端描述
        trainSignFiled: {}, // 培训报名
        channelList: [ // 报名渠道
          {
            key: this.unique(),
            channelName: '求苗',
            channelsGroup: []
          }
        ],
        buyTimes: [], // 购买起止时间  => 票务
        shelveTime: filters.FormatDate(new Date(), SHELVE_TIME_FORMAT) // 上架时间  初始值
      }
    }
  },
  methods: {
    initCateData () {
      // 初始化服务类目数据
      serviceApi.gategoryList({cateType: this.releaseType}).then(({ data = [], result, msg }) => {
        this._categoryList = data
        this.categoryList = this._recursionArr(data)
        if (this.editorType) { // 编辑
          this.getActivityData()
        }
      })
    },
    getActivityData () {
      if (this.editorType === EDIT_TYPE_ENUMS.REPUBLISH) {
        // 获取重新发布详情
        serviceApi.republishGoods({
          goodsCode: this.goodsCode
        }).then(({data}) => {
          this.initActivityData(data)
        })
      } else {
        // 获取详情
        serviceApi.editGoods({
          cateCode: this.cateCode,
          goodsCode: this.goodsCode
        }).then(({data}) => {
          this.initActivityData(data)
        })
      }
    },
    initActivityData (data) {
      this.editorData = data || {}
      this.editorData.goodsBaseInfo = JSON.parse(this.editorData.goodsBaseInfo)
      this.editorData.goodsExtInfo = JSON.parse(this.editorData.goodsExtInfo)
      this.form.serviceCate = this._getCateListByCateCode(data.goodsCateCode) // 服务类目 需要筛选显示
      this.handleCateChange(this.form.serviceCate) // 获取模板
      this.form.bizId = data.bizId // id 用于更新数据
      this.form.goodsCode = data.goodsCode // 用于更新数据
      this.form.goodsName = data.goodsName // 商品名称
      this.form.sellPoint = data.remarks // 卖点
      this.form.brand = data.brandCode // 品牌
      this.form.goodsDesc = data.descPc // 电脑描述
      this.form.attributeMappingList = data.attributeMappingList // 组别属性
      this.form.goodsSkuList = data.goodsSkuList // 库存属性
      this.form.matchChannelsList = data.matchChannelsList // 渠道属性
      this.form.goodsMoblieDesc = data.descPhone // 手机描述
      if (data.timingPublishFlag && data.timingPublishFlag - 0 === 1) {
        this.shelfLevel = SHELF_LEVEL.TIME
        this.form.shelveTime = filters.FormatDate(data.timingPublishTime, SHELVE_TIME_FORMAT)
      }
      let imgList = data.imgList || []
      this.form.imageList = imgList.map(item => { // 图片
        return item.goodsImgUrl
      })
    },
    handleCateItemChange (val) {
      // 服务类目父级菜单更改
      let cateCode = val[0]
      let index = this.categoryList.findIndex(item => {
        return item.cateCode === cateCode
      })
      let isExit = this.categoryList[index].children.length
      if (isExit) return !1
      // serviceApi.gategoryCascade({cateCode}).then(({ data, result, msg }) => {
      //   this.categoryList[index].children = data
      // })
    },
    handleCateChange (val) {
      // 初始化数据
      this.brandList = []
      this.isRun = !1
      this.isTicket = !1
      this.isTrain = !1
      this.groupItems = []
      this.form.basicProps = []
      this.form.saleProps = []
      this.form.otherProps = []
      this.form.trainSignFiled = {} // 培训
      this.$curGroupIndex = 0
      // 初始化保存草稿数据
      this.form.bizId = undefined
      this.form.goodsCode = undefined
      // this.form.tableData = []
      // 选择服务类目后
      let cateCode = val[val.length - 1] // 区最后一级
      // 获取品牌
      serviceApi.goodsBrand({cateCode}).then(({ data, result, msg }) => {
        this.brandList = data
      })
      // 获取模板
      serviceApi.goodsTemplate({
        // type: 1, // 基本属性-1 销售属性-2 其他属性-3 不传则返回全部
        goodsCateCode: cateCode
      }).then(({ data, result, msg }) => {
        // 是否赛事-跑步 在获取到数据时 在判断
        // console.log(RUN_CODE)
        this.isRun = Boolean(cateCode === RUN_CODE)
        this.isTicket = TICKET_REG.test(cateCode)
        this.isTrain = TRAIN_REG.test(cateCode)
        data.forEach(item => {
          // 数据排序 及 处理
          let fieldList = item.fieldList && item.fieldList.length ? item.fieldList.sort((a, b) => a.sortValue - b.sortValue) : []
          if (item.type === PROPS_TYPE_ENUMS.BASIC) { // 基本属性
            // 添加value valueText字段  保存对象 方便查找
            this.form.basicProps = this.getProps(fieldList, this.editorData ? this.editorData.goodsBaseInfo : [])
            // this.form.basicProps = this.form.basicProps.filter(item => item.children)
          } else if (item.type === PROPS_TYPE_ENUMS.SALE) { // 销售属性
            this.form.saleProps = fieldList.map((item, itemIndex) => {
              let values = []
              if (this.editorType) {
                values = this.form.attributeMappingList.filter(k => k.parentAttrCode === item.attrCode)
                values = values.map((vk, index) => {
                  // 根据code对应库存
                  // let skuItem = this.form.goodsSkuList.find(gk => gk.attrCodeList[0] === vk.attrCode) || {}
                  // let skuItem = this.form.goodsSkuList.find(gk => gk.skuItemList[0].attrCode === vk.attrCode) || {}
                  let skuItem = this.form.goodsSkuList.find(gk => gk.skuItemList.find(sk => sk.attrCode === vk.attrCode)) || {}
                  vk.price = skuItem.price
                  vk.num = skuItem.stock
                  vk.linmitNum = skuItem.buyTimesLimit
                  // 票务数据
                  if (this.isTicket) {
                    vk.startBuyTime = skuItem.startBuyTime
                    vk.endBuyTime = skuItem.endBuyTime
                  }
                  return vk
                })
                // 跑步特殊处理
                if (this.isRun) {
                  this.form.channelList = this.form.matchChannelsList.map(k => {
                    let channelItem = {}
                    channelItem.channelName = k.channelName
                    channelItem.channelsGroup = []
                    channelItem.editorArr = k.channelsGroup
                    // channelItem.channelsGroup = k.channelsGroup.map(kk => {
                    //   let groupItem = {}
                    //   groupItem.group = [kk.groupDes]
                    //   groupItem.lotteryNumbers = kk.lotteryNumbers
                    //   groupItem = Object.assign(BASE_TABLE_ROW_DATA, groupItem)
                    //   return groupItem
                    // })
                    return channelItem
                  })
                }
              }
              item.editorValues = values
              item.data = []
              return item
            })
          } else if (item.type === PROPS_TYPE_ENUMS.OTHER) { // 其他属性
            this.form.otherProps = this.getProps(fieldList, this.editorData ? this.editorData.goodsExtInfo : [])
            if (this.editorType) {
              if (this.isTrain) {
                // 报名选项
                let trainCourseSignupFieldList = this.editorData.trainCourseSignupFieldList
                let trainSignFileds = trainCourseSignupFieldList.map(item => {
                  let {fieldName, fieldText, isNeed} = item
                  return {fieldName, fieldText, isNeed}
                })
                this.form.trainSignFiled = {
                  values: trainSignFileds
                }
              }
            }
          }
        })
      })
    },
    getProps (propArr, valueArr = []) {
      // debugger
      let newArr = [] // 存储要显示控件的数组
      let parentIndexObj = {} // 存储显示控件attrCode的索引
      let childsObj = {} // 存储级联的对象
      let parentObj = {}
      propArr.forEach(item => {
        let assignItem = {
          value: '',
          valueText: ''
        }
        if (this.editorType) { // 编辑状态
          // 级联状态下可能最后一级没有数据 则不提交而产生找不到 默认为初始值
          let editorItem = valueArr.find(k => k.name === item.attrCode) || {}
          assignItem.editorValues = editorItem.values || ''
          assignItem.editorTexts = editorItem.valueTexts || ''
        }
        Object.assign(item, assignItem)
        let isParent = item.parentAttrCode === '0' // 是否是父级 父级都直接显示
        if (isParent) {
          newArr.push(item)
          parentIndexObj[item.attrCode] = newArr.length - 1
        } else {
          childsObj[item.attrCode] = item
        }
        parentObj[item.attrCode] = item
      })
      // 对象处理
      Object.keys(childsObj).forEach(okey => {
        let oItem = childsObj[okey]
        let pkey = oItem.parentAttrCode
        if (childsObj.hasOwnProperty(pkey)) {
          childsObj[pkey].children = oItem
          delete childsObj[okey]
        }
      })
      Object.keys(childsObj).forEach(key => {
        let childItem = childsObj[key]
        let pkey = childsObj[key].parentAttrCode
        if (parentIndexObj.hasOwnProperty(pkey)) {
          // 如果父级中能找到 直接插入 此时 为二级
          newArr[parentIndexObj[pkey]].children = childItem
        }
        delete childsObj[key]
      })
      return newArr
    },
    handleSalePropsChange ({isFirst, type, item = [], index, items}) {
      // isFirst是否初始化
      // type 修改类型 plus reduce
      // item 修改的数据
      // items 修改后的数据
      // index 多个组别时需要  预留
      // console.log(type, item, items)
      // debugger
      // console.log('groupssss')
      this.$curGroupIndex ++
      let isLast = Boolean(this.form.saleProps.length === this.$curGroupIndex)
      this.groupItems[index] = items
      item.forEach(it => {
        if (typeof it === 'string') {
          it = {
            name: it
          }
        }
        // 根据索引index去添加或者改变
        let resultGroupArr = []
        let resultItemArr = []
        this.groupItems.forEach((gk, gkIndex) => {
          if (gkIndex === 0) {
            gk.forEach(gkk => {
              resultGroupArr.push([gkk.name])
              resultItemArr.push([gkk])
            })
          } else {
            // debugger
            let tempArr = []
            let tempItemArr = []
            resultGroupArr.forEach((rk, rkIndex) => {
              gk.forEach(gkk => {
                tempArr.push([...rk, gkk.name])
                let curItem = resultItemArr[rkIndex] // 名称和对象索引一致
                tempItemArr.push([...curItem, gkk])
              })
            })
            resultGroupArr = tempArr
            resultItemArr = tempItemArr
          }
        })
        // debugger
        let newTableArr = []
        resultGroupArr.find((rk, rkIndex) => {
          let tableItem = this.form.tableData.find(k => k.group.join(',') === rk.join(','))
          if (tableItem) {
            newTableArr.push(tableItem)
          } else {
            // it.custom = it.code ? 0 : 1 // 没有code则为自定义项，custom = 1
            let curItem = resultItemArr[rkIndex]
            let addItem = Object.assign({}, BASE_TABLE_ROW_DATA, {
              group: rk,
              item: curItem,
              price: isFirst ? curItem[0].price : BASE_TABLE_ROW_DATA.price,
              num: isFirst ? curItem[0].num : BASE_TABLE_ROW_DATA.num,
              linmitNum: isFirst ? curItem[0].linmitNum : BASE_TABLE_ROW_DATA.linmitNum
            })
            newTableArr.push(addItem)
          }
          // this.form.tableData.push(addItem)
        })
        this.form.tableData = newTableArr
      })
      if (isFirst && this.editorType && isLast) {
        // 多组别时 处理库存数据
        this.form.tableData = this.form.tableData.map(tk => {
          let valueStr = tk.item.reduce((k1, k2) => (k1.skuCode || k1) + k2.skuCode)
          valueStr = typeof valueStr === 'string' ? valueStr : valueStr.skuCode // 单组别时 会返回tk.item第一个元素
          let skuItem = this.form.goodsSkuList.find(gk => {
            let name = gk.attrCodeList.join('')
            return name === valueStr
          })
          if (skuItem) {
            tk.price = skuItem.price
            tk.num = skuItem.stock
            tk.linmitNum = skuItem.buyTimesLimit
          } else {
            tk.price = BASE_TABLE_ROW_DATA.price
            tk.num = BASE_TABLE_ROW_DATA.num
            tk.linmitNum = BASE_TABLE_ROW_DATA.linmitNum
          }
          return tk
        })
      }
      if (isFirst) {
        this.$timer && clearTimeout(this.$timer)
        this.$timer = setTimeout(_ => {
          this.handleTableDataChange(this.form.tableData)
        })
      } else {
        this.handleTableDataChange(this.form.tableData)
      }
    },
    handleTableDataChange (newTableData) {
      if (this.isRun) {
        // debugger
        let channelList = this.form.channelList.map((item, index) => {
          item.editorArr = item.editorArr || []
          item.channelsGroup = item.channelsGroup || []
          let channelsGroup = []
          // item.channelsGroup = []
          newTableData.forEach((item1, index) => {
            let newData = {}
            item1 = cloneObj(item1)
            let exitChannel = item.channelsGroup.find(k => k.item[0].name === item1.item[0].name) || {}
            // if (item.channelsGroup.length - 1 >= index) {
            // } else {
            //   newData = item1
            // }
            let lotteryNumbers = exitChannel.lotteryNumbers || 0
            newData = Object.assign(exitChannel, item1)
            newData.lotteryNumbers = lotteryNumbers
            // 编辑
            let editItem = item.editorArr.find(k => k.groupDes === item1.item[0].name)
            if (editItem) {
              newData.lotteryNumbers = (editItem.lotteryNumbers - 0) || newData.lotteryNumbers
            }
            channelsGroup[index] = newData
          })
          item.channelsGroup = channelsGroup
          return item
        })
        this.form.channelList = channelList
      }
      if (this.isTicket) {
        let newBuyTimes = []
        if (newTableData.length) {
          let exitBuyTimes = this.form.buyTimes
          let firstGroupArr = this.groupItems[0] // 第一组的数据
          newBuyTimes = firstGroupArr.map(item => {
            let exitItem = exitBuyTimes.find(k => k.name === item.name) || {}
            let result = {
              name: item.name,
              label: `场次时间：${item.name}`,
              times: exitItem.times || [],
              startBuyTime: exitItem.startBuyTime || '',
              endBuyTime: exitItem.endBuyTime || ''
            }
            // 编辑状态回复默认值
            if (this.editorType && item.startBuyTime && item.endBuyTime) {
              result.startBuyTime = item.startBuyTime
              result.endBuyTime = item.endBuyTime
              result.times = [filters.FormatDate(item.startBuyTime, SHELVE_TIME_FORMAT), filters.FormatDate(item.endBuyTime, SHELVE_TIME_FORMAT)]
            }
            return result
          })
        } else {
          newBuyTimes = []
        }
        this.form.buyTimes = newBuyTimes
      }
    },
    handelAddChannel () {
      if (this.form.channelList.length >= 6) {
        return
      }
      this.form.channelList.push({
        key: this.unique(),
        channelName: '',
        channelsGroup: cloneObj(this.form.tableData)
      })
    },
    handelDelChannel (index) {
      if (index === 0) {
        this.$message({
          message: '官方渠道，不能删除',
          type: 'warning'
        })
        return !1
      }
      this.form.channelList.splice(index, 1)
    },
    handleShelfChange (newVal) { // 上架类型变动
      if (newVal === SHELF_LEVEL.TIME) {
        this.shelveTimeRules[0].required = !0
        this.shelveTimeRules[0].message = '请选择定时上架时间'
        this.form.shelveTime = ''
      } else {
        // 默认赋值 防止表单验证不通过
        this.form.shelveTime = filters.FormatDate(new Date(), SHELVE_TIME_FORMAT)
      }
    },
    handleDraft () { // 保存草稿箱
      // console.log('保存草稿箱')
      this.validate(() => {
        this.draftLoading = !0
        let subData = this.getSubData()
        serviceApi.draft(JSON.stringify(subData), {
          context: this,
          successMsg: '草稿保存成功'
        }).then(({ data }) => {
          this.draftLoading = !1
          // 保存 草稿不刷新页面  直接存编辑数据  这些数据 需要在切换类目清除
          this.form.bizId = data.bizId
          this.form.goodsCode = data.goodsCode
          // 跳转草稿箱 暂时不跳转
          // this.$router.push('/drafts')
        })
      })
    },
    submit () { // 提交后台数据
      /*
      *第二个是前面定义的options参数,options是一个对象，有context,successMsg,errorMsg
      *context:可以为vue对象或者元素对象(button)
      *successMsg:表单提交成功的提示语,默认提示语与context相关，当context为vue对象则提示"提交成功",元素对象则提示"操作成功"，不需要提交语则successMsg = 'none'
      *errorMsg:表单提交失败的提示语,默认提示语与context相关，当context为vue对象则提示"提交失败",元素对象则提示"操作失败"，不需要提交语则errorMsg = 'none'
      */
      this.saveLoading = !0
      let subData = this.getSubData()
      serviceApi.release(JSON.stringify(subData), {context: this}).then(() => {
        // this.saveLoading = !1
        // 跳转
        let nextTouter = '/service/list/check' // 默认跳审核中
        if (this.isTicket) { // 立即发布，是跳到到进行中，定时的跳到仓库中
          nextTouter = subData.shelveTime ? '/service/list/store' : '/service/list/underway'
        }
        this.$router.push(nextTouter)
      }).catch(() => {
        this.saveLoading = !1
      })
    },
    getSubData () {
      let subData = {}
      let formData = this.form
      // 更新必须
      if (this.editorType !== EDIT_TYPE_ENUMS.REPUBLISH) { // 非重新发布的编辑都需要
        subData.bizId = formData.bizId
        subData.goodsCode = formData.goodsCode
      }
      // 固定属性
      subData.cateCode = formData.serviceCate[formData.serviceCate.length - 1]
      subData.goodsName = formData.goodsName
      subData.sellPoint = formData.sellPoint
      subData.brand = formData.brand // 品牌
      subData.imageList = formData.imageList
      subData.goodsDesc = formData.goodsDesc
      subData.goodsMoblieDesc = formData.goodsDesc
      // subData.goodsMoblieDesc = formData.goodsMoblieDesc
      // 基本属性
      subData.baseFieldList = []
      formData.basicProps.map(item => {
        let {value, valueText, attrCode, attrName, showModel, sortValue} = item
        let resultItem = {
          sort: sortValue, // 排序
          name: attrCode,
          nameText: attrName,
          valueType: showModel,
          custom: 0 // 销售属性自定义项传1  其他传0
        }
        showModel = item.children ? FORM_TYPE_ENUMS.CASCADER : showModel
        if (showModel === FORM_TYPE_ENUMS.CASCADER) { // 级联
          let vItemTemp = ''
          value = value || []
          value.forEach((vItem, vIndex) => {
            resultItem = cloneObj(resultItem)
            if (vIndex === 0) {
              // 第一级的数据 默认取item
              resultItem.values = [vItem + '']
              resultItem.valueTexts = [valueText[vIndex]]
              vItemTemp = item.children
            } else if (vItemTemp) {
              resultItem.name = vItemTemp.attrCode
              resultItem.nameText = vItemTemp.attrName
              resultItem.valueType = vItemTemp.showModel
              resultItem.values = [vItem + '']
              resultItem.valueTexts = [valueText[vIndex]]
              vItemTemp = vItemTemp.children
            }
            subData.baseFieldList.push(resultItem)
          })
        } else {
          resultItem.values = value
          resultItem.valueTexts = valueText
          subData.baseFieldList.push(resultItem)
        }
      })

      // 销售属性
      subData.saleFieldList = formData.tableData.map(tableItem => {
        let fieldList = []
        let {
          group,
          item,
          num = 0,
          linmitNum = 0, // 限制购买次数
          price = 0
        } = tableItem
        // 需要确定 fieldList 各属性值传递什么
        fieldList = group.map((groupIt, index) => {
          let saleItem = formData.saleProps[index]
          let it = item[index]
          // debugger
          return {
            name: saleItem.attrCode,
            nameText: saleItem.attrName,
            values: [it.value || ''],
            valueTexts: [groupIt], // 肯定有值
            custom: it.custom // 销售属性自定义项传1  其他传0
          }
        })
        let result = {
          fieldList,
          buyLimit: linmitNum,
          number: num,
          price: price
        }
        // 票务需要增加起止时间
        if (this.isTicket) {
          // 根据第一组的名称 获取起止时间
          let buyTimeItem = formData.buyTimes.find(k => k.name === group[0]) || {}
          let {startBuyTime, endBuyTime} = buyTimeItem
          result.startBuyTime = startBuyTime
          result.endBuyTime = endBuyTime
        }
        return result
      })
      // 其他属性
      subData.otherFieldList = []
      formData.otherProps.forEach(item => {
        let {value, valueText, attrCode, attrName, showModel, sortValue} = item
        let resultItem = {
          sort: sortValue, // 排序
          name: attrCode,
          nameText: attrName,
          valueType: showModel,
          custom: 0 // 销售属性自定义项传1  其他传0
        }
        showModel = item.children ? FORM_TYPE_ENUMS.CASCADER : showModel
        if (showModel === FORM_TYPE_ENUMS.CASCADER) { // 级联
          let vItemTemp = ''
          value.forEach((vItem, vIndex) => {
            resultItem = cloneObj(resultItem)
            if (vIndex === 0) {
              // 第一级的数据 默认取item
              resultItem.values = [vItem]
              resultItem.valueTexts = [valueText[vIndex]]
              vItemTemp = item.children
            } else if (vItemTemp) {
              resultItem.name = vItemTemp.attrCode
              resultItem.nameText = vItemTemp.attrName
              resultItem.valueType = vItemTemp.showModel
              resultItem.values = [vItem]
              resultItem.valueTexts = [valueText[vIndex]]
              vItemTemp = vItemTemp.children
            }
            // 插入
            subData.otherFieldList.push(resultItem)
          })
        } else {
          resultItem.values = value
          resultItem.valueTexts = valueText
          // 插入
          subData.otherFieldList.push(resultItem)
        }
      })
      // 跑步渠道
      if (this.isRun) {
        let channelItem = this.form.channelList.map(item => {
          let channelName = item.channelName
          let channelsGroup = item.channelsGroup.map(cgItem => {
            let resultItem = {}
            resultItem.groupType = cgItem.item[0].value
            resultItem.groupDes = cgItem.item[0].name // 赛事组别类型描述
            resultItem.lotteryNumbers = cgItem.lotteryNumbers // 名额
            return resultItem
          })
          return {
            channelName,
            channelsGroup
          }
        })
        subData.extendFieldLsit = [{
          name: 'matchChannelsList',
          valueType: 5,
          values: [JSON.stringify(channelItem)],
          valueTexts: [JSON.stringify(channelItem)]
        }]
      }
      // 是否需要审核
      if (this.isTicket) {
        // 如果不为定时上架 则不传
        subData.shelveTime = this.shelfLevel === SHELF_LEVEL.TIME ? Date.parse(formData.shelveTime) : undefined
      }
      if (this.isTrain) {
        subData.extendFieldLsit = [formData.trainSignFiled]
      }
      // subData.extendFieldLsit = formData.extendFieldLsit.map(item => {
      //   // 拓展属性
      // })
      return subData
    },
    _getCateListByCateCode (cateCode) {
      // 通过类目code 从平级目录中获取全路径code
      let cateCodeArr = []
      let cateItem = this._categoryList.find(item => item.cateCode === cateCode)
      if (cateItem) {
        cateCodeArr = [cateCode]
        let pArr = this._getCateListByCateCode(cateItem.parentCateCode)
        cateCodeArr = pArr.concat(cateCodeArr)
      }
      return cateCodeArr
    },
    _recursionArr (reArr) { // 平级类目转换层树状类目
      let newArr = []
      let childObj = {}
      // let i = 0
      reArr.forEach((item, index) => {
        if (item.parentCateCode - 0 === 0) {
          newArr.push(item)
          // arr.splice(index, 1)
        } else {
          if (childObj.hasOwnProperty(item.parentCateCode)) {
            childObj[item.parentCateCode].push(item)
          } else {
            childObj[item.parentCateCode] = [item]
          }
        }
        // console.log('循环次数===' + i++)
      })
      function recursion (itemArr, obj) {
        itemArr = itemArr.map(item2 => {
          // console.log('循环次数===' + i++)
          if (obj.hasOwnProperty(item2.cateCode)) {
            item2.children = obj[item2.cateCode]
          }
          if (item2.children) {
            item2.children = recursion(item2.children, obj)
          }
          return item2
        })
        // console.log(flag)
        return itemArr
      }
      return recursion(newArr, childObj)
    }
  }
}
</script>
<style lang="scss">
  .group-table{
    .el-table__empty-block{
      border-bottom: 1px solid #f0f0f0;
      border-right: 1px solid #f0f0f0;
    }
  }
  .serviceCas.is-disabled{
    &.el-cascader{
      opacity: 1;
    }
    .el-input.is-disabled{
      z-index: auto;
    }
    .el-cascader__label{
      border: 1px solid #f0f0f0;
      color: #999;
      background: #fafafa;
    }
  }
</style>
<style lang="scss" scoped>
  .sale-props-item{
    .group-title{
      display: block;
      text-align:left;
    }
  }
  .logo-upload {
    width: 160px;
    height: 90px;
  }

  .run-type {
    width: 50px;
    text-align: right;
    display: inline-block;
  }

  .mb10 {
    margin-bottom: 10px;
  }

  .disabled {
    cursor: not-allowed
  }
  .tips.tips-left{
    text-align: right;
    font-size: 12px;
    color: #999;
    .num{
      color: #333;
      padding: 0 2px;
      font-weight: 700;
    }
  }
</style>
